package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;


    @Transactional
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息到菜品表dish
        this.save(dishDto);

        // 保存口味 dish_flavor
        List<DishFlavor> flavors = dishDto.getFlavors();
        // 给每个菜品口味设置 dishId
        flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));

        // 批量保存菜品口味
        dishFlavorService.saveBatch(flavors);

    }

    /*
    * 根据id查询菜品信息和对应的口味信息
    * */
    @Override
    public DishDto getByIdWithFlavor(Long id) {

        //查询菜品基本信息，从dish表查询
        Dish dish = this.getById(id);

        //2、查询口味数据
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id",id);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);

        //3、合并 dish + dishFlavorList = dishDto
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(dishFlavorList);

        return dishDto;

    }

    @Override
    @Transactional
    public void updateByIdWithFlavor(DishDto dishDto) {
        //1、先更新菜品数据
        this.updateById(dishDto);

        //2、清空菜品对应的所有口味数据
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id",dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        //3、添加提交的所有口味数据
        List<DishFlavor> dishFlavorList = dishDto.getFlavors();

        // 给每个菜品口味设置 dishId
        dishFlavorList.forEach(dishFlavor -> dishFlavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(dishFlavorList);

    }


}
